import React, { useState } from "react";
//引入组件
import {
  Button,
  Input,
  Form,
  Popconfirm,
  Table,
  Typography,
  Modal,
  Transfer,
} from "antd";

//引入图标库
import { FormOutlined, DeleteOutlined } from "@ant-design/icons";
//引入样式表
import "./CharacterSet.css";

export default function CharacterSet() {
  // 查询表单

  //表格区
  const originData = [];
  for (let i = 0; i < 100; i++) {
    originData.push({
      key: i.toString(),
      name: `Edrward ${i}`,
      age: 32,
      address: `London Park no. ${i}`,
    });
  }
  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCheckModalOpen, setCheckModalOpen] = useState(false);
  const isEditing = (record) => record.key === editingKey;
  //操作方法
  // 编辑
  const edit = (record) => {
    form.setFieldsValue({
      name: "",
      age: "",
      address: "",
      ...record,
    });
    setEditingKey(record.key);
  };
  const cancel = () => {
    setEditingKey("");
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  //删除
  const showDelModal = (record) => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //授权
  const mandate = (record) => {};

  //查看角色人员
  // const checkStaff = () => {};
  const [mockData, setMockData] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);
  const getMock = () => {
    const tempTargetKeys = [];
    const tempMockData = [];

    for (let i = 0; i < 20; i++) {
      const data = {
        key: i.toString(),
        title: `content${i + 1}`,
        description: `description of content${i + 1}`,
        chosen: Math.random() * 2 > 1,
      };

      if (data.chosen) {
        tempTargetKeys.push(data.key);
      }

      tempMockData.push(data);
    }

    setMockData(tempMockData);
    setTargetKeys(tempTargetKeys);
  };
  const filterOption = (inputValue, option) =>
    option.description.indexOf(inputValue) > -1;
  const handleChangeAll = (newTargetKeys) => {
    setTargetKeys(newTargetKeys);
  };
  const handleSearch = (dir, value) => {
    console.log("search:", dir, value);
  };
  const showCheckModal = (record) => {
    setCheckModalOpen(true);
    getMock();
  };
  const handleCheckOk = () => {
    setCheckModalOpen(false);
  };
  const handleCheckCancel = () => {
    setCheckModalOpen(false);
  };

  // 表格列
  const columns = [
    {
      title: "角色ID",
      dataIndex: "name",
      width: "10%",
      editable: true,
    },
    {
      title: "角色名称",
      dataIndex: "age",
      width: "15%",
      editable: true,
    },
    {
      title: "维护人",
      dataIndex: "address",
      width: "25%",
      editable: true,
    },
    {
      title: "维护日期",
      dataIndex: "date",
      width: "10%",
      editable: true,
    },
    {
      title: "备注",
      dataIndex: "note",
      width: "20%",
      editable: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginRight: 8 }}
            >
              Save
            </Typography.Link>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
              style={{ marginRight: 10 }}
            >
              <FormOutlined />
            </Typography.Link>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={showDelModal}
              style={{ marginRight: 10 }}
            >
              <DeleteOutlined />
            </Typography.Link>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => mandate(record)}
              style={{ marginRight: 10 }}
            >
              授权
            </Typography.Link>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={showCheckModal}
              style={{ marginRight: 10 }}
            >
              查看角色人员
            </Typography.Link>
          </>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <>
      {/* 查询表单 */}
      <div className="headForm">
        <div>
          角色名称:
          <Input style={{ width: 120 }} placeholder="请输入角色名称" />
        </div>

        <div>
          权限ID:
          <Input style={{ width: 120 }} placeholder="权限ID" />
        </div>
        <div>
          权限名称:
          <Input style={{ width: 120 }} placeholder="权限名称" />
        </div>
        <div>
          <Button type="primary">查询</Button>
        </div>
      </div>
      {/* 表格区域 */}
      <div className="tableArea">
        <div className="addBtn">
          <Button type="primary">添加</Button>
        </div>
        <div>
          <Form form={form} component={false}>
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              bordered
              dataSource={data}
              columns={mergedColumns}
              rowClassName="editable-row"
              pagination={{
                onChange: cancel,
              }}
            />
          </Form>
        </div>
      </div>
      {/* 删除模态框 */}
      <Modal
        title="删除确认"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>确定删除该角色吗?</p>
      </Modal>
      {/* 查看角色人员 */}
      <Modal
        title="角色人员"
        open={isCheckModalOpen}
        onOk={handleCheckOk}
        onCancel={handleCheckCancel}
        width={400}
        // height={700}
      >
        <div className="checkTransfer">
          <div>未分配该角色的用户</div>
          <div>拥有该角色的用户</div>
        </div>

        <Transfer
          dataSource={mockData}
          showSearch
          filterOption={filterOption}
          targetKeys={targetKeys}
          onChange={handleChangeAll}
          onSearch={handleSearch}
          render={(item) => item.title}
        />
      </Modal>
    </>
  );
}
